﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Xml;
using System.Diagnostics;

namespace UFSControl
{
    public partial class ArchivList : Form
    {
        private string vTimerURL;
        private string vStreamUrl;
        private string vMediaPlayer;
        private Stack<string> vDirStack = new Stack<string>(); 

        public ArchivList()
        {
            InitializeComponent();

            //Adresse einlesen
            IniFile lIni = new IniFile();
            var lip = lIni.Read("IP", "Receiver");
            vTimerURL = "http://" + lip + ":9000/xmlfeeds/archiveTable";
            vStreamUrl = "http://" + lip + ":49152/content/internal-recordings/rootContainer/record/archiveId/FileName.ts";
            vMediaPlayer = lIni.Read("EXE", "Mediaplayer");

            GenerateArchivTable("");
        }

        //an eine WEbadresse einen REquest schicken und das Ergebnis als String zurückliefern
        private string SendWebRequest(Uri aURL)
        {
            string lresponseFromServer = "";

            WebRequest lRequest = WebRequest.Create(aURL);
            ((HttpWebRequest)lRequest).UserAgent = "Eigenbau";
            lRequest.Method = "GET";
            lRequest.ContentType = "text/html";
            //Stream ldataStream = lrequest.GetRequestStream();
            // Set the 'Timeout' property in Milliseconds.
            lRequest.Timeout = 10000;
            try
            {
                // Get the response.
                WebResponse lResponse = lRequest.GetResponse();

                // Get the stream containing content returned by the server.
                Stream ldataStream = lResponse.GetResponseStream();
                // Open the stream using a StreamReader for easy access.
                StreamReader lreader = new StreamReader(ldataStream);
                // Read the content.
                lresponseFromServer = lreader.ReadToEnd();

                // Clean up the streams.
                lreader.Close();
                ldataStream.Close();
                lResponse.Close();
                return lresponseFromServer;
            }
            catch
            {
                //Timeout abfangen
                MessageBox.Show("Request timed out");
                return ""; //Programm verlassen

            }
        }

        private string PrintDayOfWeek(DayOfWeek day)
        {
            switch (day)
            {
                case DayOfWeek.Monday:
                    return "Mo";
                case DayOfWeek.Tuesday:
                    return "Di";
                case DayOfWeek.Wednesday:
                    return "Mi";
                case DayOfWeek.Thursday:
                    return "Do";
                case DayOfWeek.Friday:
                    return "Fr";
                case DayOfWeek.Saturday:
                    return "Sa";
                case DayOfWeek.Sunday:
                    return "So";
            }
            return "  ";

        }

        private void GenerateArchivTable(string aFolderNr)
        {
            Uri lUri = new Uri(vTimerURL);
            if (aFolderNr != "")  //Unterverzeichnis angefordert, Request dahingehend erweitern
            {
                lUri =  new Uri(vTimerURL + lUri + "?folder-nr=" + aFolderNr);
            }
            string lresponseFromServer = SendWebRequest(lUri);
            if (lresponseFromServer == "") return;
            //Liste leeren
            ArchiveListView.Items.Clear();
            //XML Elemente durchgehen
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(lresponseFromServer);
            XmlElement root = doc.DocumentElement;
            XmlNodeList nodes = root.SelectNodes("./recordingevent");
            try
            {
                string title = "";
                string catIcon = "";
                string archiveNo = "";
                string parentFolder = "";
                string rootContainer = "";
                string isFolder = "";
                string zeit = "";
                string startTime = "";
                string duration = "";
                string channelName = "";
                string mainCat = "";
                DateTime UnixEpoch;
                foreach (XmlNode i in nodes)
                {
                    title = i["title"].InnerText;
                    if (i["archiveNo"] != null) { archiveNo = i["archiveNo"].InnerText; } else { archiveNo = ""; }
                    if (i["parentFolderNo"] != null) { parentFolder = i["parentFolderNo"].InnerText; } else { parentFolder = ""; }
                    if (i["rootContainer"] != null) { rootContainer = i["rootContainer"].InnerText; } else { rootContainer = ""; }
                    if (i["isFolder"] != null) { isFolder = (i["rootContainer"].InnerText = "1"); } else { isFolder = "Nein"; }
                    if (i["catIcon"] != null) { catIcon = i["catIcon"].InnerText; } else { catIcon = ""; }
                    if (i["channelName"] != null) { channelName = i["channelName"].InnerText; } else { channelName = ""; }
                    if (i["mainCat"] != null) { mainCat = i["mainCat"].InnerText; } else { mainCat = ""; }

                    if (i["startTime"] != null)
                    {
                        startTime = i["startTime"].InnerText;
                        UnixEpoch = new DateTime(Convert.ToInt64(i["startTime"].InnerText) * 10000000); //Ticks
                        UnixEpoch = UnixEpoch.AddHours(1); //Timeoffset 1 Stunde addieren
                        UnixEpoch = UnixEpoch.AddYears(1969); //TimeOffset, das richtige Jahr auswählen
                        zeit = String.Format("{0} {1:00}.{2:00}.{3:00} {4:00}:{5:00}", PrintDayOfWeek(UnixEpoch.DayOfWeek), UnixEpoch.Day, UnixEpoch.Month, UnixEpoch.Year - 2000, UnixEpoch.Hour, UnixEpoch.Minute);
                    }
                    else
                    {
                        zeit = "";
                        startTime = "";
                    }
                    if (i["duration"] != null){ duration = i["duration"].InnerText + " min";}
                    ListViewItem listItem = ArchiveListView.Items.Add(new ListViewItem(new string[] { "", title, zeit, duration, archiveNo, parentFolder, rootContainer, isFolder, channelName, mainCat }));
                    if (catIcon != "")
                    {
                        string Icon = catIcon;
                        Icon = Icon.Replace("/icon/", "");
                        //Icon aus der Liste suchen
                        (listItem).ImageIndex = Convert.ToInt16(Icon);

                    }
                    else
                    {
                        (listItem).ImageIndex = 0;
                    }
                }
            }
            catch
            {
            }


        }

        private void streamToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string stream = vStreamUrl;
            string archiveId = ArchiveListView.SelectedItems[0].SubItems[4].Text;
            string rootContainer = ArchiveListView.SelectedItems[0].SubItems[6].Text;
            string FileName = ArchiveListView.SelectedItems[0].SubItems[1].Text;
            //im Dateinamen müssen alle Leerzeichen mit #20 ersetzt werden
            FileName = FileName.Replace(" ", "#20");
            stream = stream.Replace("archiveId", archiveId); //ArchivNr URL einfügen
            stream = stream.Replace("rootContainer", rootContainer); //Container in URL einfügen
            stream = stream.Replace("FileName", FileName); //Filename in URL einfügen
            try
            {
                Process.Start(vMediaPlayer, stream);
            }
            // Most specific:
            catch (Win32Exception ex)
            {
                MessageBox.Show("Streaming Client konnte nicht gefunden werden: " + ex.Message);
            }
            // Least specific:
            catch (Exception ex)
            {
                MessageBox.Show("Fehler beim öffnen des Streaming Clients: " + ex.Message);
            }
        }

        private void ArchiveListView_DoubleClick(object sender, EventArgs e)
        {
            //handelt es sich um ein Verzeichnis?
            if (ArchiveListView.SelectedItems[0].SubItems[7].Text == "1")
            {
                if (ArchiveListView.SelectedItems[0].SubItems[1].Text == ".."){
                    //1 Ebene höher
                    string ParentDir = vDirStack.Pop();
                    GenerateArchivTable(ParentDir);
                }
                else
                {
                    //1 Ebene tiefer
                    vDirStack.Push(ArchiveListView.SelectedItems[0].SubItems[5].Text); //Parent Directory merken
                    GenerateArchivTable(ArchiveListView.SelectedItems[0].SubItems[4].Text);
                }
            }
            else
            {
                streamToolStripMenuItem_Click(sender, e);
            }
        }

    }
}
